<template>
	<view>
		<view class="zhtx-imgs">
			<view class="zhtx-single" v-for="(item,index) in imageList" :key="index">
				<image :src="item" :data-src="item" @tap="previewImg" mode="aspectFill" style="width:180rpx ;height: 180rpx;"/>
				<view class="zhtx-del" @tap="deleteItem(index)">x</view>
			</view>
			<view v-if="limit>imageList.length" class="zhtx-single zhtx-addNew" @tap="chooseFile"
				style="display: flex; flex-direction: column;justify-content: center;align-items: center;">
				<image src="../../static/img/plus.png" alt="" class="img-add" style="width:180rpx ;height: 180rpx;">
				<text style="font-size: 12px;">{{placeHolderText}}</text>
			</view>
		</view>
<!-- 
		<view class="watermark-canvas">
			<canvas id="watermark-canvas" :style="{ width: canvasWidth, height: canvasHeight }"
				canvas-id="watermark-canvas" />
		</view> -->

	</view>
</template>

<script>
	let toast = msg => {
		uni.showToast({
			title: msg,
			icon: 'none'
		});
	}
	import {
		url
	} from "../../pin.js"

	export default {
		props: {

			placeHolderText: {
				type: String,
				default: ""
			},
			initImgs: {
				type: Array,
				default: () => []
			},

			imgSrc: {
				type: String,
				default: '../../static/img/addimg.png'
			},
			limit: {
				default: 1, //这里有问题???
				type: Number, //限制可上传的图片数量
			},
			imageType: {
				type: String,
				default: 'id_card'
			},
			fileKeyName: {
				type: String,
				default: 'file' //用于在服务端通过自定义key值获取该文件数据
			},
			canUploadFile: { //是否更新
				type: Boolean,
				default: true
			},
			watermark: {
				type: Boolean,
				default: true,
			},
		},
		mounted() {
			this.imageList = this.initImgs
		},
		watch: {
			initImgs(val) {
				this.imageList = val
			},
		},
		computed: {
			// imageList:function(){
			// 	var arr =[];
			// 	arr = this.imgSrc
			// 	return arr

			// }
		},
		data() {
			return {
				canvasWidth: '180rpx',
				canvasHeight: '180rpx',
				imageList: [], //给父亲组件传值
				list: [],
				addImg: require('@/static/img/add.png'),
				uploadFileUrl: url + '/assets/generate',
				header: {
					"Content-Type": "multipart/form-data",
					'authorization': uni.getStorageSync('token')
				}
			};
		},
		methods: {
			//预览
			previewImg(e) {
				console.log(...this.imageList);
				uni.previewImage({
					current: e.target.dataset.src,
					loop: true,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					},
					urls: this.imageList //this.imageList,保持删除了的不在
				});
			},
			//删除
			deleteItem(index) {

				uni.showModal({
					title: '提示',
					content: '确定要删除此项吗？',
					success: res => {
						if (res.confirm) {
							this.list.splice(index, 1);
							this.imageList.splice(index, 1);
							this.$forceUpdate(); //强制更新
							// this.$emit('update:uImgList', this.list); //类似双向数据绑定
							this.$emit('uploadSuccess', this.imageList);

						}
					}
				});
			},

			async chooseFile() {
				// 双重保证
				console.log(this.imageList.length, 'limit', this.limit);
				if (this.imageList.length >= this.limit) {
					toast('已达到最大上传数量')
					return;
				}

				var that = this;
				// let canUploadFile = this.canUploadFile;
				// let tempFiles;

				var res = await this.choose();
				let url = res.tempFilePaths[0];
				if (that.watermark) {
					// url = await that.addWatermark(res.tempFilePaths[0])
				}
				that.imageList.push(url)

				this.OneImgUploadToOss(res.tempFiles[0], res.tempFilePaths[0]);

			},


			async choose() {
				return new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['original', 'compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							resolve(res)
						},
						fail: err => {
							console.log(err);
						}
					});


				})

			},





			// async addWatermark(tempFilePath) {
			// 	console.log(tempFilePath)
			// 	return new Promise((resolve, reject) => {
			// 		uni.getImageInfo({
			// 			src: tempFilePath,
			// 			success: async (res) => {
			// 				console.log("---" + res.path)
			// 				// 设置画布高度和宽度
			// 				this.canvasWidth = `${res.width}px`
			// 				this.canvasHeight = `${res.height}px`
			// 				// await this.sleep(200) // 某些平台 canvas 渲染慢，需要等待

			// 				const ctx = uni.createCanvasContext('watermark-canvas', this)
			// 				ctx.clearRect(0, 0, res.width, res.height)
			// 				ctx.beginPath()
			// 				ctx.drawImage(res.path, 0, 0, res.width, res.height)

			// 				// 水印 字体大小，颜色，内容，位置
			// 				ctx.beginPath()
			// 				ctx.setFontSize(38)
			// 				ctx.setFillStyle('rgba(255,0,0,0.6)')
			// 				ctx.fillText('盈盈糖', res.width / 2 - 60, res.height - 180)
			// 				ctx.fillText('盈盈糖', res.width / 2 - 60, res.height - 120)
			// 				ctx.fillText('盈盈糖', res.width / 2 - 60, res.height - 60)
			// 				// 开始绘制 (canvas -> 临时文件路径)
			// 				ctx.draw(false, async () => {
			// 					// await this.sleep(500) // 某些平台 canvas 渲染慢，需要等待

			// 					uni.canvasToTempFilePath({
			// 							canvasId: 'watermark-canvas',
			// 							destWidth: res.width,
			// 							destHeight: res.height,
			// 							fileType: 'jpg',
			// 							quality: 0.8,
			// 							success: (fileRes) => {
			// 								resolve(fileRes.tempFilePath)
			// 							},
			// 							fail: (err) => {
			// 								console.log('[Error draw]', err)
			// 								uni.showToast({
			// 									title: err.errMsg,
			// 									icon: 'none'
			// 								})
			// 								reject()
			// 							},
			// 						},
			// 						this,
			// 					)
			// 				})
			// 			},
			// 			fail: (err) => {
			// 				console.log('[Error getImageInfo]', err)
			// 				uni.showToast({
			// 					title: err.errMsg,
			// 					icon: 'none'
			// 				})
			// 				reject()
			// 			},
			// 		})
			// 	})
			// },



			OneImgUploadToOss(file, filePath) {
				uni.showLoading({
					title: '上传中...',
					mask: false
				});
				var that = this;
				this.$pin.getUploadParams(that.imageType,
					data => {
						console.log(data)
						const formData = {};
						const filename = this.$pin.getUUID() + '.' + filePath.substr(filePath.lastIndexOf('.') + 1)

						formData.name = filename;
						formData.OSSAccessKeyId = data.access_id;
						formData.policy = data.policy;
						formData.success_action_status = '200';
						formData.signature = data.signature;
						formData.key = data.dir + '/' + filename;
						formData.file = file;

						uni.uploadFile({
							url: data.host,
							filePath,
							name: 'file',
							formData,
							success: (uploadFileRes) => {
								console.log(uploadFileRes.data);

								// 获取图片
								this.$pin.generateAsset(formData.key, filename, that.imageType,
									success => {
										console.log("success:" + success.id)
										//传给父组件
										that.list.push(success.id);
										uni.hideLoading()

										that.$emit('uploadSuccess', this.list);

									},
									error => {
										uni.hideLoading()

									}
								)

							},
							error: (error) => {
								uni.hideLoading()

								console.log(error.data);
							},
						})



					},
					fail => {

					}
				)
			},





			// 单张图片上传
			// OneImgUpload(path) {
			// 	uni.showLoading({
			// 		title: '上传中...',
			// 		mask: false
			// 	});
			// 	var that = this
			// 	let index = this.list.length;
			// 	var that = this;

			// 	that.imageList.push(path);

			// 	//传给父组件
			// 	// that.$emit('uploadSuccess', this.imageList);
			// 	uni.uploadFile({
			// 		url: that.uploadFileUrl,
			// 		name: that.fileKeyName,
			// 		filePath: path, // 使用files上传数组列表,上面两者都会失效
			// 		header: that.header,
			// 		formData: {
			// 			path: path,
			// 			file_name: that.fileKeyName,
			// 			type: "ID_CARD"
			// 		},
			// 		success: res => {
			// 			uni.hideLoading()
			// 			console.log(res);
			// 			if (res.statusCode == 401) {
			// 				console.log("token 过期，需要登录")
			// 				// uni.removeStorageSync("token")
			// 				uni.redirectTo({
			// 					url: '/pages/splash-screen/splash-screen'
			// 				})
			// 				return
			// 			}
			// 			var data = JSON.parse(res.data)
			// 			console.log(data.data, "data")
			// 			that.list.push(data.data.src)
			// 			that.imageList.push(data.data.src)
			// 			that.$forceUpdate();
			// 			that.$emit('uploadSuccess', this.imageList);
			// 			uni.showToast({
			// 				title: '上传成功'
			// 			})

			// 		},
			// 		fail: err => {

			// 			uni.hideLoading()
			// 			toast(err.errMsg)
			// 			console.log(err);
			// 		}
			// 	})


			// },
			// 多张图片上传
			// upload() {
			// 	uni.showLoading({
			// 		title: '上传中...',
			// 		mask: false
			// 	});
			// 	var that = this
			// 	for (let i = 0; i < this.list.length; i++) {
			// 		let path = this.list[i]
			// 		let index = i.toString()
			// 		console.log('path', path);
			// 		uni.uploadFile({
			// 			url: that.uploadFileUrl,
			// 			name: that.fileKeyName,
			// 			filePath: path, // 使用files上传数组列表,上面两者都会失效
			// 			header: that.header,
			// 			formData: {
			// 				photoType: 1
			// 			},
			// 			// file: [{
			// 			// 	name: index,
			// 			// 	url: path,
			// 			// }],
			// 			success: res => {
			// 				uni.hideLoading()
			// 				console.log(res);
			// 				this.$emit('uploadSuccess', res);
			// 				if (res.statusCode == 200) {
			// 					//上传成功将原信息,直接删除,
			// 					// this.list.splice(i, 1)
			// 					console.log(this.list);
			// 					console.log(res);
			// 					this.$forceUpdate();
			// 				} else {

			// 				}
			// 			},
			// 			fail: err => {
			// 				uni.hideLoading()
			// 				toast(err.errMsg)
			// 				console.log(err);
			// 			}
			// 		})

			// 	}

			// },

		}
	};
</script>

<style scoped>
	.zhtx-imgs {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
		width: 100%;
		/* justify-content: center; */
	}

	.zhtx-del {
		position: absolute;
		width: 35rpx;
		height: 35rpx;
		background: #f56c6c;
		color: #fff;
		top: 0;
		text-align: center;
		right: 0;
		line-height: 28rpx;
		font-size: 30rpx;
		z-index: 100;
	}

	.zhtx-single {
		position: relative;
		width: 180rpx;
		height: 180rpx;
		/* border: 1px solid #ccc; */
		margin-top: 10rpx;
		margin-right: 30rpx;
	}

	.zhtx-addNew {
		display: flex;
		justify-content: center;
		align-items: center;
		border: 0.8px dotted #e6e6e6;

	}

	.watermark-canvas {
		position: absolute;
		top: 5px;
		left: 5px;
		width: 1px;
		height: 1px;
		overflow: hidden;
	}

	.img-add {
	
	}

	text {
		font-size: 50rpx;
		color: #999;
	}

	image {
		width: 100%;
		height: 100%;
		display: block;
	}
</style>